package com.example.databasepj.service;

import com.example.databasepj.Request.OrderData;
import com.example.databasepj.Request.OrderRequest;
import com.example.databasepj.dto.DishData;
import com.example.databasepj.dto.MerchantOrderResponse;
import com.example.databasepj.dto.OrderDetail;
import com.example.databasepj.dtoAdvanced.*;
import com.example.databasepj.entity.*;
import com.example.databasepj.exception.BusinessException;
import com.example.databasepj.exception.ErrorCode;
import com.example.databasepj.mapper.*;
import org.apache.ibatis.exceptions.PersistenceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

@Service
public class OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private MerchantMapper merchantMapper;
    @Autowired
    private MessageMapper messageMapper;

    public void insertOrderAndDetail (OrderRequest orderRequest){
        //先创建order
        OrderEntity newOrder = new OrderEntity();
        newOrder.setOrder_form(orderRequest.getOrder_form());
        newOrder.setMerchant_id(orderRequest.getMerchant_ID());
        newOrder.setUser_id(orderRequest.getUser_ID());
        newOrder.setOrder_status(0);//订单状态为已下单

        LocalDateTime now = LocalDateTime.now();
        // 定义日期时间格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");
        String formattedNow = now.format(formatter);
        newOrder.setCreate_time(now);
        int newOrder_id;
        try{
            newOrder_id=orderMapper.insertOrder(newOrder);//若成功插入则返回id

        }catch(PersistenceException e){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR);
        }
        //再创建orderDetail
        newOrder_id=newOrder.getOrder_id();
        List<OrderDetailEntity> orderDetailEntities =new ArrayList<>();
        for(int i=0;i<orderRequest.getOrderData().size();i++){
            OrderData orderData=orderRequest.getOrderData().get(i);
            OrderDetailEntity newOrderDetail = new OrderDetailEntity(newOrder_id,orderData.getDish_ID(),orderData.getQuantity());
            try {
                orderDetailMapper.insertOrderDetail(newOrderDetail);
            }catch(PersistenceException e){
                throw new BusinessException(ErrorCode.SYSTEM_ERROR);
            }
        }
    }

    //用户查看所有订单信息
    public List<OrderDetail> getUserOrderList(int user_id){
        List<OrderDetail> result =new ArrayList<>();
        //先查看user的order
        List<OrderEntity> orderEntities=orderMapper.selectOrderByUserID(user_id);
        for(int i=0;i<orderEntities.size();i++){
            int order_id=orderEntities.get(i).getOrder_id();
            OrderEntity orderEntity=orderEntities.get(i);
            OrderDetail order = new OrderDetail(order_id,orderEntity.getMerchant_id());
            order.setCreate_time(orderEntity.getCreate_time());
            if(orderEntity.getOrder_form()==0){
                order.setOrder_form("排队点餐");
            }
            else {
                order.setOrder_form("在线点餐");
            }

            if(orderEntity.getOrder_status()==0){
                order.setOrder_status("已下单");
            }
            else {
                order.setOrder_status("已完成");
            }
            //根据orderid获取orderDetail
            List<OrderDetailEntity> orderDetails=orderDetailMapper.selectOrderDetailByOrderID(order_id);
            List<DishData> dishList = new ArrayList<>();
            for(int j=0;j<orderDetails.size();j++){
                //根据detail里的dishId获取其他信息
                int dish_ID=orderDetails.get(j).getDish_id();
                DishEntity dish=dishMapper.selectDishByDishId(dish_ID);
                DishData dishData = new DishData(dish_ID,dish.getDish_name(),dish.getPrice(),orderDetails.get(j).getQuantity());
                dishList.add(dishData);
            }
            order.setDishList(dishList);
            result.add(order);
        }
        return result;
    }

    public void updateOrderStatus(int orderID, int orderStatus){
        //更新状态信息
        orderMapper.updateOrder_status(orderID,orderStatus);
        //插入一个新message
        OrderEntity order = orderMapper.selectOrderByOrderID(orderID);
        // this.message_id = message_id;
        //        this.user_id = user_id;
        //        this.merchant_id = merchant_id;
        //        this.message_type = message_type;
        //        this.message_content = message_content;
        //        this.time = time;
        LocalDateTime now = LocalDateTime.now();
        MessageEntity messageEntity=new MessageEntity(order.getUser_id(),order.getMerchant_id());
        messageEntity.setTime(now);
        messageEntity.setMessage_type(1);//订单完成消息
        MerchantEntity merchant = merchantMapper.selectMerchantById(messageEntity.getMerchant_id());
        messageEntity.setMessage_content("您的订单已完成！请尽快到以下窗口取餐：\n商家："+merchant.getMerchant_name()+"\n地址:"+merchant.getAddress());
        messageMapper.insertMessage(messageEntity);

    }
    public List<MerchantOrderResponse> merchantGetOrders(int merchantID){
        List<OrderEntity> orderEntities = orderMapper.selectOrderByMerchantID(merchantID);
        List<MerchantOrderResponse> results=new ArrayList<>();
        for(int i=0;i<orderEntities.size();i++){
            OrderEntity orderEntity = orderEntities.get(i);
            MerchantOrderResponse response = new MerchantOrderResponse(orderEntity.getOrder_id(),orderEntity.getOrder_status());
            results.add(response);
        }
        return results;

    }
    public List<FansResponse> getFans(FansRequest request){
        //将时间从string转换到localtime
        LocalDate startTime=parseDateString(request.getStart_date());
        LocalDate endTime=parseDateString(request.getEnd_date());
        //如果时间顺序正确
        if (isStartDateBeforeEndDate(request)){
            FansMiddleRequest middleRequest = new FansMiddleRequest(request.getMerchant_ID(), startTime,endTime, request.getThreshold());
            List<FansMiddleData> fansID=orderMapper.selectFans(middleRequest);

            List<FansResponse> results =new ArrayList<>();
            for(int i=0;i<fansID.size();i++){
                results.add(new FansResponse(fansID.get(i).getUserID()));
            }
            return results;
        }else {
            return null;
        }

    }

    //将时间字符串转换为localDateTime
    public LocalDate parseDateString(String dateString) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        return LocalDate.parse(dateString, formatter);
    }
    public boolean isStartDateBeforeEndDate(FansRequest request) {
        LocalDate startDate = parseDateString(request.getStart_date());
        LocalDate endDate = parseDateString(request.getEnd_date());
        return startDate.isBefore(endDate);
    }
    public boolean isStartDateBeforeEndDate(FanConsumptionRequest request) {
        LocalDate startDate = parseDateString(request.getStart_date());
        LocalDate endDate = parseDateString(request.getEnd_date());
        return startDate.isBefore(endDate);
    }


    public List<FansConsumptionResponse> getFansConsumption(FanConsumptionRequest request){
        //将时间从string转换到localtime
        LocalDate startTime=parseDateString(request.getStart_date());
        LocalDate endTime=parseDateString(request.getEnd_date());
        //如果时间顺序正确
        if (isStartDateBeforeEndDate(request)){
            FansConsumptionMiddleRequest middleRequest = new FansConsumptionMiddleRequest(request.getMerchant_ID(), request.getUser_ID(), startTime,endTime);
            List<FansConsumptionResponse> results = orderMapper.getFansConsumption(middleRequest);
            return results;
        }else {
            return null;
        }
    }
}
